<template>
  <TablePage>
    <template #top>
      <SearchForm
        title="设备管理"
        :keyword-search-data="[{ key: 'videoCameraName', label: '摄像机名称' }]"
        @search="search"
      >
        <template #extraButtons>
          <a-button class="mr-2" type="primary" ghost @click="exportDevice">导出</a-button>
          <a-button type="primary" :loading="loadingDeviceType" @click="showCreateModal">新增设备</a-button>
        </template>
      </SearchForm>
    </template>
    <SlTable :columns="columns" row-key="id" :data-source="tableData" :pagination="pagination" :loading="tableLoading">
      <template #bodyCell="{ column, record }">
        <div v-if="column.key === 'oper'">
          <a @click="showUpdateModal(record)">编辑</a>
          <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
        </div>
        <a-tag
          v-else-if="column.dataIndex === 'openDetection'"
          :color="record.openDetection === 0 ? 'success' : 'error'"
        >
          {{ record.openDetection === 0 ? "已开启" : "已关闭" }}
        </a-tag>
        <div v-else-if="column.dataIndex === 'deviceType'">
          {{ loadingDeviceType ? "加载中..." : getTypeName(record.deviceType) }}
        </div>
      </template>
    </SlTable>
    <CURDDialog
      id-key="id"
      :columns="columns"
      create-title="新增设备"
      update-title="编辑设备"
      delete-message="确认删除该设备吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :model-rules="modelRules"
      :table-data="tableData"
      :oper-data="operData"
      :curd="curd"
      :reload-table="reloadTable"
      @before-ok="beforeOk"
    />
  </TablePage>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { useCURD } from "/@/hooks/useCURD";
import { downloadFile, handleDateRowRender } from "/@/utils/common";
import { FormItemComponentType, CURDAction, CURDModalEvent } from "/@/components/CURDDialog/models";
import type { FormItemData, OperItem, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import type { TableProps } from "ant-design-vue";
import { PatternKey } from "/@/utils/verify";
import { Api, getDeviceType } from "/@/api/main/civilizedService";
import { DeviceItem, DeviceTypeItem } from "/@/api/main/civilizedService/models";
import { exportReq } from "/@/api/common";

const { t } = useI18n();

const deviceTypeData = ref<DeviceTypeItem[]>([]);
const loadingDeviceType = ref(true);
onMounted(async () => {
  const data = await getDeviceType();
  if (data) {
    deviceTypeData.value = data;
  }
  loadingDeviceType.value = false;
});
function getTypeName(typeId: number) {
  const el = deviceTypeData.value.find((el) => el.typeId === typeId);
  return el ? el.typeName : "--";
}

const columns = ref<TableProps<DeviceItem>["columns"]>([
  // {
  //   title: "服务器IP",
  //   dataIndex: "videoServerIp",
  // },
  {
    title: "端口",
    dataIndex: "port",
  },
  {
    title: "设备名称",
    dataIndex: "videoCameraName",
  },
  {
    title: "设备类型",
    dataIndex: "deviceType",
  },
  {
    title: "登录用户名",
    dataIndex: "videoCameraUsername",
  },
  {
    title: "设备IP",
    dataIndex: "videoCameraIp",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    customRender: handleDateRowRender,
  },
  {
    title: t("common.oper"),
    key: "oper",
    width: 100,
  },
]);
function search(model) {
  reloadTable({ model });
}
const model = ref<DeviceItem>({
  // videoServerIp: "",
  port: "",
  videoCameraName: "",
  videoCameraUsername: "",
  videoCameraPassword: "",
  deviceType: null,
  videoCameraIp: "",
  // openDetection: 1,
  // qualifiedScore: 0,
  // keywords: "",
});
const modelRules = [
  // "videoServerIp",
  "port",
  "videoCameraName",
  "videoCameraUsername",
  "videoCameraPassword",
  "videoCameraIp",
  "qualifiedScore",
];
const modelFormSetting: FormItemData<DeviceItem>[] = [
  // {
  //   key: "videoServerIp",
  //   pattern: PatternKey.ipAddress,
  // },
  {
    key: "port",
    type: FormItemComponentType.NUMBER,
  },
  {
    key: "videoCameraName",
    pattern: PatternKey.name,
    max: 100,
  },
  {
    key: "videoCameraUsername",
    pattern: PatternKey.name,
    max: 100,
  },
  {
    key: "videoCameraPassword",
    label: "摄像机密码",
    type: FormItemComponentType.PASSWORD,
  },
  {
    key: "videoCameraIp",
    pattern: PatternKey.ipAddress,
  },
  {
    key: "deviceType",
    type: FormItemComponentType.SELECT,
    required: true,
    async getData() {
      return deviceTypeData.value.map((el) => ({ label: el.typeName, value: el.typeId }));
    },
    props: {
      options: [],
    },
  },
  // {
  //   key: "keywords",
  //   type: FormItemComponentType.TEXT,
  //   label: "关键字",
  // },
  // {
  //   key: "qualifiedScore",
  //   type: FormItemComponentType.NUMBER,
  // },
  // {
  //   key: "openDetection",
  //   type: FormItemComponentType.SWITCH,
  //   props: {
  //     checkedValue: 0,
  //     unCheckedValue: 1,
  //   },
  // },
];
function beforeOk({ model }: CURDModalEvent) {
  //将服务器IP隐藏并默认值为127.0.0.1
  if (model) {
    model.videoServerIp = "127.0.0.1";
  }
}

const showOptions = ref<ShowCURDModalOptions>();

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<DeviceItem>({
  getPageUrl: Api.devicesPage,
  updateUrl: Api.devicesPage,
  createUrl: Api.devicesPage,
  deleteUrl: Api.devicesPage,
});

const operData: OperItem<DeviceItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
  },
];
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
async function exportDevice() {
  const re = await exportReq(Api.devicesExport, {});
  if (re) {
    downloadFile(re, "设备列表");
  }
}
</script>
